package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.query.TravelQueryObject;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.LoginUser;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import cn.wolfcode.luowowo.website.util.UploadUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/travel")
public class TravelController {

    @Value("${file.dir}")
    private String dir;

    @Reference
    private ITravelService travelService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private ITravelCommentService travelCommentService;

    @RequestMapping("")
    public Object list(@ModelAttribute("qo") TravelQueryObject qo, Model model) {
        //pageInfo对象
        model.addAttribute("pageInfo", travelService.query(qo));
        return "travel/list";
    }

    @RequestMapping("/detail")
    public Object detail(Long id, Model model) {

        //detail 查询文章的内容
        Travel travel = travelService.get(id);
        TravelContent content = travelService.getContent(id);
        System.out.println(content);
        travel.setTravelContent(content);
        model.addAttribute("detail", travel);

        //目的地的id
        Long destId = travel.getDest().getId();

        //toasts 吐司(先拿到目的地的id再进行吐司查询操作)
        List<Destination> toasts = destinationService.listToast(destId);
        model.addAttribute("toasts", toasts);
        //dest 目的地
        model.addAttribute("dest", toasts.remove(toasts.size() - 1));

        //sds  查询该目的地下面点击量前3的攻略
        model.addAttribute("sds", strategyDetailService.listViewnumTop3(destId));

        //ts  查询该目的地下面点击量前3的游记
        model.addAttribute("ts", travelService.listViewunmTop3(destId));

        //list 当前游记的评论
        model.addAttribute("list", travelCommentService.listByTravelId(id));

        return "travel/detail";
    }

    @RequiredLogin              //登录的用户才可以精心`进行该操作
    @RequestMapping("/input")
    public Object input(Long id, Model model) {       //注意:当更新操作时就会有id,故需要id
        if (id != null) {
            //不查询文章的内容,由页面发起ajax异步亲求查询文章的内容
            model.addAttribute("tv", travelService.get(id));
        }
        //dests 目的地
        model.addAttribute("dests", destinationService.listDests());
        return "travel/input";
    }

    @RequiredLogin              //登录的用户才可以  进行该操作
    @ResponseBody
    @RequestMapping("/saveOrUpdate")
    public Object saveOrUpdate(Travel entity, @LoginUser UserInfo userInfo) {
        //设置登录用户
        entity.setAuthor(userInfo);
        AjaxResult result = travelService.saveOrUpdate(entity);
        return result;
    }

    //获取游记的内容
    @RequestMapping("/getContent")
    @ResponseBody
    public Object getContent(Long id) {
        return travelService.getContent(id);
    }

    //游记封面的文件上传
    @RequestMapping("coverImageUpload")
    @ResponseBody
    public Object coverImageUpload(MultipartFile pic) {
        //直接返回上传文件      注意:要对应二进制文件的名字需要和前台页面对应,否则会失败
        return UploadUtil.upload(pic, dir);
    }

    //UME上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        java.lang.String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, dir);
        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }

    /**
     * 游记评论
     * 资源：
     * /travel/commentAdd
     * 参数：
     * travelId=xx
     * travelTitle=xx
     * type=xx
     * refComment.id=xx
     * floor=xx
     * 返回：
     * { success: true }
     *
     * @return
     */
    @RequiredLogin
    @RequestMapping("/commentAdd")
    public Object commentAdd(TravelComment entity, Integer floor, @LoginUser UserInfo userInfo, Model model) {
        //添加用户的信息
        entity.setUserId(userInfo.getId());
        entity.setUsername(userInfo.getNickname());
        entity.setHeadUrl(userInfo.getHeadImgUrl());
        entity.setLevel(userInfo.getLevel());
        //保存游记的评论
        entity = travelCommentService.save(entity);

        //c 游记评论对象(记得传入对象,否则数据出错.
        model.addAttribute("c",entity);

        //floor 评论的楼层数
        model.addAttribute("floor",floor + 1);
        return "travel/commentTpl";

    }
}
